<?php

namespace app\api\controller;
use app\admin\db\Field;
use app\BaseController;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use xhadmin\db\User;
use xhadmin\db\Group;
use think\App;
use think\View;

class Base extends BaseController
{
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;

    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;

    public $userInfo = [];

    /**
     * 构造方法
     * @access public
     * @param  App  $app  应用对象
     */
    public function __construct(App $app,View $view)
    {

        $this->app     = $app;
        $this->request = $this->app->request;
        $this->view = $view;

        // 控制器初始化
        $this->initialize();
    }
    // 初始化
    protected function initialize()
    {
        $this->auth();
    }
   
	/**
     * 授权管理
     * @return array|string
     */
    public function auth()
    {
        $headerInfo = Request::header();
        $pathinfo = explode('/',Request::instance()->pathinfo());
        $controller = !empty($pathinfo[0]) ? str_replace('.html','',$pathinfo[0]) : 'Index';
        if(strtolower($controller) != 'login'){
            //p($headerInfo);
            if(!isset($headerInfo['token']) || empty($headerInfo['token'])) {
                $this->returnMsg(401,'令牌不正确');
            }
            $token = trim($headerInfo['token']);
            $info = Db::name("user")
                ->field('*')
                ->where(['tokin_id'=>$token])
                ->find();
            $now = time();
            if(!$info){
                $this->returnMsg(401,'token错误');
            } else {
                if(!$info['status']) {
                    $this->returnMsg(500,'账号被锁定');
                }
                if(($now - $info['update_time']) > Config::get('session.expire')){
                    $this->returnMsg(401,'token过期');
                }
                //获取成功
                $systoper = [
                    //'login_last_ip' => ip(),
                    'update_time' => time()
                ];
                Db::name('user')
                    ->where(['tokin_id'=>$token])
                    ->update($systoper);
                $this->userInfo = $info;
            }
        }
        //echo $token;exit;

    }


	//清除缓存 出去session缓存
	public function clearData(){
		$dir = config('my.clear_cache_dir') ? app()->getRootPath().'/runtime/api' : app()->getRootPath().'/runtime';
		if(deldir($dir) && deldir(app()->getRootPath().'runtime/')){
			return json(['status'=>'00']);
		}
	}

    protected function returnMsg($code, $msg = '', $data = [])
    {
        $return_data['code'] = $code;
        $return_data['msg'] = $msg;
        $return_data['data'] = $data;
        header('Content-type: application/json');
        echo json_encode($return_data);die;
    }
	

}
